import AuthComponent from '@/components/Authorized/AuthComponent';
import React, { useState, useEffect, useRef } from 'react';
import { Table, DatePicker, Select, Button, Modal, message, Radio } from 'antd';
import { useRequest } from '@umijs/hooks';

import ProTable from '@ant-design/pro-table';
import styles from './index.less'

import { controlTableHeight } from '@/utils/pagesGeneralMethods'; // 页面通用方法
import {queryCityInfo, queryCounterTable, deleteData, saveData} from './service'

import ImportModal from './components/importModal'
import FormModal from './components/formModal'
export default function () {

  const actionRef = useRef();
  const formRef = useRef();

  // const [isCollapse, controlC] = useState(true); //搜索面板是否折叠
  const height = document.body.clientHeight - 320; // 表格高度自适应

  const { data: selectData } = useRequest(queryCityInfo,{loadingDelay: true}); //获取出发和到达航站

  const [queryParams, setqueryParams] = useState({});
  const [selectedRows, handleSelectedRows] = useState([]);
  const [selectedRowKeys, handleSelectedRowKeys] = useState([]) // 勾选索引

  const [formModalVisible, setFormModalVisible] = useState(false)
  const [formData, setFormData] = useState({})
  const [formType, setFormType] = useState('')
  // 上传模态框
  const [AddExcelModalVisible, handleAddExcel] = useState(false);

  const addOrEdit = async (fields) => {
    let text = formType === 'add' ? '新增' : '编辑'
    const hide = message.loading('正在'+text)
    try {
      let res = await saveData(fields);
      if (res.code === '0') {
        hide();
        message.success(text+'成功');
        return true;
      } else {
        hide();
      }
    } catch (error) {
      hide();
      message.error(text+'失败请重试！');
      return false;
    }
  }
  const delHandle = async () => {
    try {
      await deleteData(
        selectedRows.map(row => row.id),
      );
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
      return false;
    }
  }
  const importHandle = () => {
    handleAddExcel(true)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) =>{
      handleSelectedRowKeys(selectedRowKeys)
      handleSelectedRows(selectedRows)
    }
  };
  const columns = [
    { title: '始发地', dataIndex: 'orgPlace',width: 90,
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select
            style={{ width: '100%' }}
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
          >
            {selectData && selectData.length > 0 &&
              selectData.map((v, i) => {
                return (
                  <Select.Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Select.Option>
                )
              })
            }
          </Select>
        );
      }
    },
    { title: '到达地', dataIndex: 'dstPlace', width: 90,
      renderFormItem: (_, { ...rest }) => {
        return (
          <Select
            style={{ width: '100%' }}
            allowClear={true}
            showSearch
            placeholder="请选择"
            defaultActiveFirstOption={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
          >
            {selectData && selectData.length > 0 &&
              selectData.map((v, i) => {
                return (
                  <Select.Option key={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Select.Option>
                )
              })
            }
          </Select>
        );
      }
    },
    { title: '当前价格（元）', dataIndex: 'price', hideInSearch: true, width: 140},
    { title: '当前价格（外币）', dataIndex: 'foreignPrice', hideInSearch: true, width: 160,
      render: (_, row) => {
        let foreignPrice = row.foreignPrice ? row.foreignPrice+'（' : '-'
        let foreignPriceUnit = row.foreignPriceUnit ? row.foreignPriceUnit +'）' : ''
        return foreignPrice + foreignPriceUnit
      }
    },
    { title: '生效价格（元）', dataIndex: 'effectPrice', hideInSearch: true, width: 140},
    { title: '生效价格（外币）', dataIndex: 'effectForeignPrice', hideInSearch: true, width: 160,
      render: (_, row) => {
        let effectForeignPrice = row.effectForeignPrice ? row.effectForeignPrice+'（' : '-'
        let effectForeignPriceUnit = row.effectForeignPriceUnit ? row.effectForeignPriceUnit+'）' : ''
        return effectForeignPrice  + effectForeignPriceUnit 
      }
    },
    { title: '生效时间', dataIndex: 'effectTime',width: 120,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{width: '100%'}}
            format={format}
            {...rest}
          />
        )
      },
    },
    { title: '状态', dataIndex: 'status', hideInSearch: true, width: 90,
      valueEnum: {
        0: {text: '停用',},
        1: {text: '启用'},
      },
    },
    { title: '编辑人', dataIndex: 'updateUser', hideInSearch: true, width: 120,},
    { title: '最后编辑时间', dataIndex: 'updateTime', hideInSearch: true, width: 160},
  ]
  return (
    <>
      <ProTable
        className={ `${styles.counterUpgradeTable} `}
        actionRef={actionRef}
        formRef={formRef}
        columns={columns}
        headerTitle={
          <span style={{ paddingRight: 10, fontWeight: 'bold', color: '#000' }}>柜台升舱维护表</span>
        }
        rowSelection={rowSelection}
        rowKey="id"
        tableAlertRender={false}
        options={{density: false,fullScreen:true, reload:false, setting:true}}
        // scroll={{y: controlTableHeight(isCollapse, 360, 470), x: 1100 }}
        scroll={{x: 1100, y: 222}}
        search={{
          // onCollapse:val => {
          //   controlC(val);
          // },
          span: { //设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
        request = {params=>{
          if (!params.effectTime) {
            // ref.current.setFieldsValue({
            //   effectTime: ''
            // })
          } else {
            params['effectTime'] = params.effectTime ? params.effectTime.format('YYYY-MM-DD') : '';
          }
          return queryCounterTable(params)
        }}
        postData={data => data}
        toolBarRender={() => [
          <div className={styles.btnWrapper}>
            <AuthComponent authCode="mkt.counterUpgrade.save">
            <Button onClick={()=>{
              setFormType('add')
              setFormData({})
               setFormModalVisible(true)
            }}>新建</Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.counterUpgrade.save">
            <Button onClick={()=>{
              if (selectedRows.length > 1) {
                message.error('只能选择一条进行编辑');
              } else if (selectedRows.length === 0) {
                message.error('请选择编辑的条目');
              } else {
                setFormType('edit')
                setFormModalVisible(true)
                setFormData(selectedRows[0])
              }
            }}>编辑</Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.counterUpgrade.delete">
            <Button onClick={()=>{
              if (selectedRowKeys.length === 0) {
                message.error("请选择删除的条目")
              } else {
                Modal.confirm({
                  title: '提示',
                  content: '确认操作后该条目将被删除，你还要继续吗？',
                  onOk: async () => {
                    let res = await delHandle(selectedRows)
                    if (res) {
                      actionRef.current.reload();
                      handleSelectedRows([])
                      handleSelectedRowKeys([])
                    }
                  }
                })
              }
            }}>删除</Button>
            </AuthComponent>
            <AuthComponent authCode="mkt.counterUpgrade.import">
            <Button type="primary" onClick={importHandle}>批量导入</Button>
            </AuthComponent>
          </div>
        ]}
      ></ProTable>
      <ImportModal
        onCancel={() => handleAddExcel(false)}
        addExcel={AddExcelModalVisible}
        uploadFinish={()=>{
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      />
      <FormModal
        formData={formData}
        type={formType}
        formModalVisible={formModalVisible}
        onCancel={()=>{setFormModalVisible(false)}}
        onSubmit={async (params) => {
          let res = await addOrEdit(params)
          if (res) {
            setFormModalVisible(false)
            handleSelectedRows([])
            handleSelectedRowKeys([])
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      />
    </>
  );
}
